﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Data;
using System.Xml.Serialization;
using System.Diagnostics;
/// <summary>
/// Summary description for ArrayToDataTable
/// </summary>
public class ArrayToDataTable
{
    public ArrayToDataTable()
    {
        xmlStop = new Stopwatch();
        refStop = new Stopwatch();
    }




    public Stopwatch xmlStop;
    public Stopwatch refStop;
    /// <summary>
    /// Converts an Object Array to a System.Data.DataTable using Reflection.
    /// </summary>
    /// <param name="inArray">Object array to be converted</param>
    /// <returns></returns>
    public DataTable ConvertArrayToDataTable(object[] inArray)
    {
        refStop.Start();
        //create our datatable
        DataTable dt = new DataTable();


        if (inArray.Length == 0)
            return new DataTable();
        //initialize a new type of our inArray type
        Type type = inArray[0].GetType();


        //extract all our properties (public & static) from our type (generic)
        PropertyInfo[] proInfo = type.GetProperties();


        //create the columns for each property setting the name & type (generic)
        foreach (PropertyInfo i in proInfo)
            dt.Columns.Add(i.Name, i.PropertyType);


        //loop through each object in the array
        foreach (object o in inArray)
        {
            //create a new datarow
            DataRow r = dt.NewRow();
            //loop through each property in order and set our row columns to the value of the property
            for (int i = 0; i < proInfo.Length; i++)
                r[i] = o.GetType().InvokeMember(proInfo[i].Name, BindingFlags.GetProperty, null, o, null);


            //add the row to our table
            dt.Rows.Add(r);
        }
        refStop.Stop();
        return dt;
    }


    /// <summary>
    /// Converts an object Array to a DataTable using XML Serialization.
    /// </summary>
    /// <remarks>Not recommended for use. Use Reflection method</remarks>
    /// <param name="inArray">object Array to be converted</param>
    /// <returns></returns>
    public DataTable ConvertArrayToDataTableXML(object[] inArray)
    {
        xmlStop.Start();
        Type type = inArray.GetType();
        XmlSerializer serializer = new XmlSerializer(type);
        System.IO.StringWriter sw = new System.IO.StringWriter();
        serializer.Serialize(sw, inArray);
        System.Data.DataSet ds = new System.Data.DataSet();
        System.Data.DataTable dt = new System.Data.DataTable();
        System.IO.StringReader reader = new System.IO.StringReader(sw.ToString());


        ds.ReadXml(reader);
        dt = ds.Tables[0];
        xmlStop.Stop();
        return dt;
    }
}